package com.example.note2;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class CRUD {
    SQLiteOpenHelper dbHandler; // 数据库处理器
    SQLiteDatabase db;

    // 数组，用于存储数据库表的列名
    private static final String[] columns = {
            NoteDatabase.ID,
            NoteDatabase.CONTENT,
            NoteDatabase.TIME,
            NoteDatabase.MODE,
            NoteDatabase.USER_ID // 新增用户 ID
    };

    public CRUD(Context context) {
        dbHandler = new NoteDatabase(context);
    }

    // 打开数据库, 获取可写数据库
    public void open() {
        db = dbHandler.getWritableDatabase();
    }

    public void close() {
        db.close(); // 关闭数据库
    }

    // 添加笔记到数据库，传入 userId
    public Note addNote(Note note) {
        ContentValues contentValue = new ContentValues();
        contentValue.put(NoteDatabase.CONTENT, note.getContent());
        contentValue.put(NoteDatabase.TIME, note.getTime());
        contentValue.put(NoteDatabase.MODE, note.getTag());
        contentValue.put(NoteDatabase.USER_ID, note.getUserId()); // 存储用户 ID

        // 返回 id，数据
        long insertId = db.insert(NoteDatabase.TABLE_NAME, null, contentValue);
        note.setId(insertId);
        return note;
    }
    public boolean authenticateUser(String username, String password) {
        SQLiteDatabase db = dbHandler.getReadableDatabase();
        Log.d("CRUD", "Authenticating user: " + username);

        Cursor cursor = db.query(NoteDatabase.USER_TABLE_NAME,
                new String[]{NoteDatabase.USER_NAME, NoteDatabase.USER_PASSWORD},
                NoteDatabase.USER_NAME + "=?",
                new String[]{username},
                null, null, null);

        boolean isAuthenticated = false;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") String storedPassword;
                storedPassword = cursor.getString(cursor.getColumnIndex(NoteDatabase.USER_PASSWORD));
                isAuthenticated = storedPassword.equals(password); // 验证密码
            }
            cursor.close();
        }
        return isAuthenticated; // 返回是否验证成功
    }
    public long addUser(String username, String password) {
        ContentValues values = new ContentValues();
        values.put(NoteDatabase.USER_NAME, username);
        values.put(NoteDatabase.USER_PASSWORD, password);

        long newRowId = db.insert(NoteDatabase.USER_TABLE_NAME, null, values);

        if (newRowId == -1) {
            Log.e("CRUD", "User insert failed: " + username);
        } else {
            Log.i("CRUD", "User inserted with ID: " + newRowId);
        }
        return newRowId;
    }

    // 根据 ID 查询单个笔记
    public Note getNote(long id) {
        Cursor cursor = db.query(NoteDatabase.TABLE_NAME,
                columns,
                NoteDatabase.ID + "=?",
                new String[]{String.valueOf(id)},
                null,
                null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            Note e = new Note(
                    cursor.getString(1),
                    cursor.getString(2),
                    cursor.getInt(3),
                    cursor.getString(4) // 获取用户 ID
            );
            cursor.close(); // 记得关闭 cursor
            return e;
        }
        return null; // 如果没有找到，返回 null
    }

    // 基于用户 ID 查询所有笔记
    public List<Note> getAllNotes(String userId) {
        Cursor cursor = db.query(NoteDatabase.TABLE_NAME,
                columns,
                NoteDatabase.USER_ID + "=?", // 只获取当前用户的笔记
                new String[]{userId},
                null,
                null,
                null);
        List<Note> notes = new ArrayList<>();

        if (cursor != null && cursor.getCount() > 0) {
            int idColumnIndex = cursor.getColumnIndex(NoteDatabase.ID);
            int contentColumnIndex = cursor.getColumnIndex(NoteDatabase.CONTENT);
            int timeColumnIndex = cursor.getColumnIndex(NoteDatabase.TIME);
            int modeColumnIndex = cursor.getColumnIndex(NoteDatabase.MODE);

            if (idColumnIndex != -1 && contentColumnIndex != -1 &&
                    timeColumnIndex != -1 && modeColumnIndex != -1) {
                while (cursor.moveToNext()) {
                    Note note = new Note();
                    note.setId(cursor.getLong(idColumnIndex));
                    note.setContent(cursor.getString(contentColumnIndex));
                    note.setTime(cursor.getString(timeColumnIndex));
                    note.setTag(cursor.getInt(modeColumnIndex));
                    note.setUserId(cursor.getString(4)); // 设定用户 ID
                    notes.add(note);
                }
            } else {
                // 处理列名不存在的情况
                throw new IllegalArgumentException("One or more column names do not exist in the cursor.");
            }
            cursor.close(); // 记得关闭 cursor
        }
        return notes;
    }

    // 更新笔记
    public int updateNote(Note note) {
        ContentValues values = new ContentValues();
        values.put(NoteDatabase.CONTENT, note.getContent());
        values.put(NoteDatabase.TIME, note.getTime());
        values.put(NoteDatabase.MODE, note.getTag());
        // 更新笔记，条件是 ID 匹配
        return db.update(NoteDatabase.TABLE_NAME, values,
                NoteDatabase.ID + "=?", new String[]{String.valueOf(note.getId())});
    }

    // 删除笔记
    public void removeNote(Note note) {
        db.delete(NoteDatabase.TABLE_NAME, NoteDatabase.ID + "=" + note.getId(), null);
    }
    public long getUserIdByUsername(String username) {
        long userId = -1; // 默认返回值为 -1，表示未找到或发生错误
        SQLiteDatabase db = dbHandler.getReadableDatabase();
        Cursor cursor = null;

        try {
            cursor = db.query(NoteDatabase.USER_TABLE_NAME,
                    new String[]{NoteDatabase.USER_ID},
                    NoteDatabase.USER_NAME + "=?",
                    new String[]{username},
                    null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                // 如果找到用户，获取其 ID
                userId = cursor.getLong(cursor.getColumnIndex(NoteDatabase.USER_ID));
            }
        } catch (Exception e) {
            Log.e("CRUD", "Error retrieving user ID for username: " + username, e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return userId; // 返回用户 ID 或 -1
    }


}
